const db = require("../../lib/db");

//获取日记
exports.getDiaryPage = (pageSize, nowPage, searchTerm) => {
    let _sql;
    let params = [];
    
    if (searchTerm) {
      _sql = `SELECT * FROM diary WHERE concat(title,content) like ? order by id desc limit ?, ?`;
      params = [`%${searchTerm}%`, (nowPage - 1) * pageSize, pageSize];
    } else {
      _sql = `SELECT * FROM diary order by id desc limit ?, ?`;
      params = [(nowPage - 1) * pageSize, pageSize];
    }
    return db.queryWithPool(_sql, params);
  }
  
  //获取日记总数
  exports.getDiaryCount = (searchTerm) => {
    let _sql;
    let params = [];
    
    if (searchTerm) {
      _sql = `SELECT count(*) AS count FROM diary WHERE concat(title,content) like ?`;
      params = [`%${searchTerm}%`];
    } else {
      _sql = `SELECT count(*) AS count FROM diary`;
      params = [];
    }
    return db.queryWithPool(_sql, params);
  }

  //新建日记
exports.addDiary = (value) => {
    let _sql = `INSERT INTO diary set ?`;
    return db.queryWithPool(_sql, value);
  }
  
  //删除日记
  exports.deleteDiary = (id) => {
    let _sql = `DELETE FROM diary WHERE id = ?`;
    return db.queryWithPool(_sql, [id]);
  }